package com.portal.sso.core.server.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.model.JwtModel;
import com.portal.sso.core.model.ResponseTModel;
import com.portal.sso.core.server.JwtServerHander;
import com.portal.sso.core.server.VerificationTgtServer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Data
public class VerificationTgtServerImpl extends VerificationTgtServer {

   private JwtServerHander jwtServerHander;

    private String clientAppId;
    private String clientSecret;

    @Override
    public String Verification(String ver_url, String tgt) {
        try {
            if(StrUtil.isEmpty(tgt)) return null;
            String result = HttpRequest.post(ver_url)
                    .header(SsoConfig.SSO_HEADER_TGT, tgt)//tgt头信息
                    .form(SsoConfig.SSO_APP_ID,clientAppId)
                    .execute().body();
            ResponseTModel model = JSONUtil.toBean(result, ResponseTModel.class);
            if (model.getCode() == 500) {
                return null;
            }
            JwtModel jwtModel = JSONUtil.toBean(model.getData().toString(), JwtModel.class);
           return CheckUserId(jwtModel.getJwt());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 解析jwt获取userid
     * @param jwt
     * @return 返回用户userid
     */
    @Override
    public String CheckUserId(String jwt) {
        Map map = jwtServerHander.verifyToken(jwt,clientSecret);
        if(map!=null){
          return   map.get(SsoConfig.SSO_USER_ID).toString();
        }
        return null;
    }


}
